#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define SERVER_IP "192.168.253.132" // 服务器IP地址
#define BUFFER_SIZE 1024

int main() {
    int sock;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];
    const char *message = "Hello, Server!";

    // 创建 socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("Invalid address or address not supported");
        close(sock);
        exit(EXIT_FAILURE);
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("connect failed");
        close(sock);
        exit(EXIT_FAILURE);
    }

    printf("Connected to server at %s:%d\n", SERVER_IP, PORT);

    // 客户端接收服务器的消息
    while (1) {
        int bytes_read = read(sock, buffer, sizeof(buffer));
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            printf("Received from server: %s\n", buffer);
        }

        // 用户输入消息
        printf("Enter message to send to server (or -1 to quit): ");
        fgets(buffer, sizeof(buffer), stdin);
        buffer[strcspn(buffer, "\n")] = '\0';  // 去掉换行符

        // 如果用户输入 -1，则结束通信
        if (strcmp(buffer, "-1") == 0) {
            send(sock, buffer, strlen(buffer), 0); // 发送 -1
            break;
        }

        // 发送消息
        send(sock, buffer, strlen(buffer), 0);
        printf("Message sent: %s\n", buffer);
    }

    // 关闭连接
    close(sock);

    return 0;
}
